const router = require('koa-router')()
//token加密
const { gentoken} = require("../../token/jwt")
// 操作数据库
const {
  getToken,
  Addurl,
  selurl
} = require('../../config/databaseapi')
// 解析token
const { showtoken} = require("../../token/showtoken")
const { nanoid} = require('nanoid')
const result = require('../../config/result')
// 校验
const { regcheck} = require("../../config/register")

// after 后台服务器
router.prefix('/api/after')

// 注册接口
router.post('/register', async ctx => {
  let {
    username,
    password
  } = ctx.request.body
  new regcheck(ctx, username, password).start()
  let query = `db.collection("usersettable").where({username:'${username}'}).get()`
  try {
    const user = await new getToken().postlive(selurl, query)
    if (user.data.length > 0) {
      new result(ctx, '该号码以注册过', 200).answer()
    } else {
      const uid = nanoid()
      const obj = {
        username,
        password,
        uid
      }
      const strobjs = JSON.stringify(obj)
      const query = `db.collection("usersettable").add({data:${strobjs}})`
      await new getToken().postlive(Addurl, query)
      new result(ctx, '注册成功', 200).answer()
    }
  } catch (error) {
    new result(ctx, "注册失败,服务器出现错误", 500).answer()
  }
})
//登录接口
router.post('/login', async ctx => {
  let {
    username,
    password
  } = ctx.request.body
  let query = `db.collection("usersettable").where({username:'${username}',password:'${password}'}).get()`

  try {
    const user = await new getToken().postlive(selurl, query)
    if (user.data.length == 0) {
      new result(ctx, '账号或密码错误', 202).answer()
    } else {
      const obj = JSON.parse(user.data)
      new result(ctx, "登录成功", 200, {token: gentoken(obj.uid)}).answer()
    }
  } catch (error) {
    console.log("服务器错误在哪里:", error)
    new result(ctx, "登录失败,服务器出现错误", 500).answer()
  }
})
router.post('/testl', new showtoken().m, async ctx => {
  console.log("susse", ctx.req)
  ctx.body = {
    title: "123"
  }
})

module.exports = router